package com.shareach.redis;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import redis.clients.jedis.JedisPoolConfig;

@Service("redisService")
public class RedisService implements InitializingBean, DisposableBean {
	private static Map<String, Redis> mapRedis = new HashMap<String, Redis>();
	@Autowired
	private RedisConfig redisConfig;
	private JedisPoolConfig jedisPoolConfig;
	private NewJedis jedisResource;

	@Override
	public void afterPropertiesSet() throws Exception {
		jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxActive(redisConfig.getMaxActive());
		jedisPoolConfig.setMaxIdle(redisConfig.getMaxIdle());
		jedisPoolConfig.setMaxWait(redisConfig.getMaxWait());
		jedisPoolConfig.setTestOnBorrow(redisConfig.getTestOnBorrow());
		for (RedisHost host : redisConfig.getHosts()) {
			buildRedisPool(host.getName(), host.getHost(), host.getPort(), host.getPassword());
		}
	}

	public NewJedisPool buildRedisPool(String name, String host, int port, String password) {
		NewJedisPool pool = null;
		if (StringUtils.isBlank(password)) {
			pool = new NewJedisPool(jedisPoolConfig, host, port, redisConfig.getTimeout());
		} else {
			pool = new NewJedisPool(jedisPoolConfig, host, port, redisConfig.getTimeout(), password);
		}
		// map.put(name,pool);
		mapRedis.put(name, new Redis(pool));

		if (jedisResource == null) {
			jedisResource = pool.getResource();
		}
		return pool;
	}

	/**
	 * 释放Jedis实例
	 * 
	 * @param name
	 * @param jedis
	 */
	public Redis getRedis(String name) {
		if (mapRedis.containsKey(name)) {
			return mapRedis.get(name);
		}
		throw new RuntimeException("无效Redis：" + name);
	}

	public Redis getRedis() {
		return getRedis("main");
	}

	public NewJedis getJedis() {
		return jedisResource;
	}

	@Override
	public void destroy() throws Exception {
		// for(NewJedisPool pool : map.values()){
		// if(pool!=null)
		// pool.destroy();
		// }
	}

}
